//
//  SetWXAndPayTreasureCtl.m
//  GBKTrade
//
//  Created by admin on 2019/4/19.
//  Copyright © 2019 LionIT. All rights reserved.
//

#import "SetWXAndPayTreasureCtl.h"

@interface SetWXAndPayTreasureCtl ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) UILabel *nameLab;
@property (nonatomic, strong) UITextField *nameTF;

@property (nonatomic, strong) UIButton *uploadCodeBtn;
@property (nonatomic, strong) UIButton *commitOrRemoveBtn;
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) QCCountdownButton *sendBtn;

@end

@implementation SetWXAndPayTreasureCtl
{
    UIImage *_chooseImg;
    UITextField *_nameTextField;//真实姓名
    UITextField *_accountTextField;//微信或者支付宝账号
    UITextField *_codeTF;//短信验证码
    __block NSString *_imgStr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.iconAndTitleLeftBtn setTitle:[NSString stringWithFormat:@"设置%@",self.titleName] forState:UIControlStateNormal];
    if (self.model != nil) {
        _imgStr = self.model.pictureUrl;
    }
    
    //设置UI
    [self setUpUI];
}
#warning 页面需要更改  心累 这么写
- (void)setUpUI {
    
    UIView *colorView = [[UIView alloc] init];
    colorView.backgroundColor = UIColorFromRGB(0xeeeeee);
    [self.view addSubview:colorView];
    [colorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(@0);
        make.top.mas_equalTo(NavigationStatusBarHeight);
        make.bottom.mas_offset(@0);
    }];
    
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = WhiteColor;
    [colorView addSubview:backView];
    self.backView = backView;
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(@0);
        make.top.mas_offset(@(FIT(21)));
        make.height.mas_offset(@180);
    }];
    
    //真实姓名/账号
    for (NSInteger i = 0; i < 3; i++) {
        self.nameLab = [[UILabel alloc] init];
        if (i == 0) {
            self.nameLab.frame = CGRectMake(16, 10, 100, 40);
            self.nameLab.text = @"真实姓名：";
            [self setLineViewWithRect:CGRectMake(0, 59, ScreenWidth, 1)];
        }else if (i == 2){
            self.nameLab.frame = CGRectMake(16, 70, 100, 40);
            self.nameLab.text = [NSString stringWithFormat:@"%@：",self.titleName];
            [self setLineViewWithRect:CGRectMake(0, 119, ScreenWidth, 1)];
        }else {
            self.nameLab.frame = CGRectMake(16, 130, 120, 40);
            self.nameLab.text = @"短信验证码：";
        }
        self.nameLab.tag = 100+i;
        [backView addSubview:self.nameLab];
    }

    
    //姓名设置6位限制
    for (NSInteger j = 0; j < 3; j++) {
        self.nameTF = [[UITextField alloc] init];
        self.nameTF.tag = 200+j;
        if (j == 0) {
            _nameTextField = self.nameTF;
            self.nameTF.frame = CGRectMake(121, 10, ScreenWidth-137, 40);
//            self.nameTF.keyboardType
            if (self.model != nil) {
                self.nameTF.text = self.model.realName;
            }else {
                self.nameTF.placeholder = @"请输入姓名";
            }
            
        }else if (j == 1){
            _accountTextField = self.nameTF;
            self.nameTF.frame = CGRectMake(121, 70, ScreenWidth-137, 40);
            if (self.model != nil) {
                self.nameTF.text = self.model.payAccount;
            }else {
                if ([self.titleName isEqualToString:@"支付宝"]) {
                    self.nameTF.placeholder = @"请输入支付宝账号";
                }else {
                    self.nameTF.placeholder = @"请输入微信账号";
                }
            }
            
        }else {
            _codeTF = self.nameTF;
            _codeTF.placeholder = @"请输入验证码";
            self.nameTF.frame = CGRectMake(121, 130, 130, 40);
            _sendBtn = [QCCountdownButton countdownButton];
            _sendBtn.frame = CGRectMake(ScreenWidth-116, 135, 100, 30);
            _sendBtn.title = @"获取验证码";
            // 普通状态下的背景颜色
            _sendBtn.nomalBackgroundColor = [UIColor redColor];
            // 字体
            _sendBtn.titleLabelFont = [UIFont systemFontOfSize:11];
            _sendBtn.totalSecond = 59;
            _sendBtn.layer.cornerRadius = 3;
            [_sendBtn addTarget:self action:@selector(sendAction) forControlEvents:UIControlEventTouchUpInside];
            [backView addSubview:_sendBtn];
            
            //进度b
            WeakSelf(self);
            [_sendBtn processBlock:^(NSUInteger second) {
                weakSelf.sendBtn.title = [NSString stringWithFormat:@"(%lis)后重新获取", second];
                
            } onFinishedBlock:^{  // 倒计时完毕
                weakSelf.sendBtn.title = @"重新获取验证码";
            }];
        }
        self.nameTF.returnKeyType = UIReturnKeyDone;
//        self.nameTF.tag = 200+j;
        self.nameTF.font = Font_15;
        self.nameTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        [backView addSubview:self.nameTF];
        [self.nameTF addTarget:self action:@selector(chooseTFAction:) forControlEvents:UIControlEventEditingChanged];
    }
    
    
    
    //上传收款码
    //c2c_upload_photo
    self.uploadCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.uploadCodeBtn sd_setImageWithURL:[NSURL URLWithString:self.model.pictureUrl] forState:UIControlStateNormal placeholderImage:YQ_IMAGE(@"camera")];
    
    [colorView addSubview:self.uploadCodeBtn];
    [self.uploadCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(@16);
        make.top.mas_equalTo(backView.mas_bottom).mas_offset(@16);
        make.width.height.mas_offset(@80);
    }];
    [self.uploadCodeBtn addTarget:self action:@selector(chooseImage) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *desLab = [[UILabel alloc] init];
    desLab.text = @"上传收款码";
    desLab.font = Font_15;
    desLab.textColor = [UIColor darkGrayColor];
    [colorView addSubview:desLab];
    [desLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(@16);
        make.top.mas_equalTo(self.uploadCodeBtn.mas_bottom).mas_offset(@10);
    }];
    
    self.commitOrRemoveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.commitOrRemoveBtn setBackgroundColor:MainRedTextColor];
    [self.commitOrRemoveBtn setTitle:@"提交" forState:UIControlStateNormal];
    [self.commitOrRemoveBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    self.commitOrRemoveBtn.layer.cornerRadius = 5;
    self.commitOrRemoveBtn.layer.borderColor = [UIColor clearColor].CGColor;
    self.commitOrRemoveBtn.layer.borderWidth = 0.5f;
    self.commitOrRemoveBtn.layer.masksToBounds = YES;
    [colorView addSubview:self.commitOrRemoveBtn];
    [self.commitOrRemoveBtn addTarget:self action:@selector(commitAction) forControlEvents:UIControlEventTouchUpInside];
    [self.commitOrRemoveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(@16);
        make.right.offset(-16);
        make.top.mas_equalTo(desLab.mas_bottom).mas_offset(@60);
        make.height.mas_offset(@45);
    }];
}

- (void)sendAction {
    [SZHTTPSReqManager getRequestWithUrlString:YQ_joiningTogetherUrl(@"users/tokenMsg") appendParameters:@{@"msgType":@"6"} successBlock:^(id responseObject) {
        BaseModel *base = [BaseModel modelWithJson:responseObject];
        if (base.code == 0) {
            [LCProgressHUD showSuccess:@"发送成功"];
        }else {
            [LCProgressHUD showSuccess:base.msg];
        }
    } failureBlock:^(NSError *error) {
        
    }];
}


- (void)setLineViewWithRect:(CGRect)rect {
    //分割线
//    WithFrame:CGRectMake(0, 59, ScreenWidth, 1)
    UIView *lineView = [[UIView alloc] initWithFrame:rect];
    lineView.backgroundColor = UIColorFromRGB(0xeeeeee);
    [self.backView addSubview:lineView];
}

#pragma mark - 限制输入框的字数
- (void)chooseTFAction:(UITextField *)textField {
    if (textField.tag == 200) {
        //姓名
        [LimitTextFieldNum limitTextFieldContentNumWith:textField withMaxNum:6];
    }else if (textField.tag == 201) {
        //账号
        [LimitTextFieldNum limitTextFieldContentNumWith:textField withMaxNum:20];
    }else {
        [LimitTextFieldNum limitTextFieldContentNumWith:textField withMaxNum:6];
    }
}

#pragma mark - 选择照片
- (void)chooseImage {
    //图片选择
    [self choosePickIcon];
}

- (void)choosePickIcon {
    //点击弹框选择照片 或者相机
    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
    _imagePicker.allowsEditing = YES;
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"从相机拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.imagePicker animated:YES completion:nil];
            
        }
    }];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消");
    }];
    
    [actionSheet addAction:cameraAction];
    [actionSheet addAction:photoAction];
    [actionSheet addAction:cancelAction];
    
    [self presentViewController:actionSheet animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerController *,id> *)info {
    //获取图片
    _chooseImg = info[UIImagePickerControllerOriginalImage];
//    [self.uploadCodeBtn setImage:_chooseImg forState:UIControlStateNormal];
    [self selectedImg:_chooseImg withPicker:picker];
    
}

#pragma mark - 照片上传
- (void)selectedImg:(UIImage *)backImg withPicker:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:^{
        NSString* urlString=[NSString stringWithFormat:@"%@users/fileUpload",BaseHttpUrl];
        
        [SZHTTPSReqManager postUploadWithUrl:urlString image:backImg successBlock:^(id responseObject) {
            [self.uploadCodeBtn sd_setImageWithURL:[NSURL URLWithString:responseObject[@"data"][@"resourceURL"]] forState:UIControlStateNormal placeholderImage:nil];
            _imgStr = responseObject[@"data"][@"resourceURL"];
        } successBlock:^(NSError *error) {
            
        }];
    }];
    
}

//按取消按钮时候的功能
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    // 返回
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)commitAction {
    NSString* urlStr=[NSString stringWithFormat:@"%@sys/payment-way",BaseHttpUrl];
    NSString *alipayOrWechat ;
    if ([self.titleName isEqualToString:@"支付宝"]) {
        alipayOrWechat = @"2";
    }else {
        alipayOrWechat = @"1";
    }
    
    if (isEmptyString(_nameTextField.text)) {
        [LCProgressHUD showMessage:@"请输入真实姓名"];
        return;
    }
    if (isEmptyString(_accountTextField.text)) {
        [LCProgressHUD showMessage:[NSString stringWithFormat:@"请输入%@账号",self.titleName]];
        return;
    }
    
    if (isEmptyString(_imgStr)) {
        [LCProgressHUD showMessage:@"请上传收款码"];
        return;
    }
    
    if (isEmptyString(_codeTF.text)) {
        [LCProgressHUD showMessage:@"请填写验证码"];
        return;
    }
    
    //提交
    NSDictionary *paramters = @{@"paymentWay":alipayOrWechat,
                                          @"payAccount":_accountTextField.text,
                                          @"realName":_nameTextField.text,
                                          @"pictureUrl":_imgStr,
                                          @"messageCode":_codeTF.text
                                          };
    
    [SZHTTPSReqManager postRequestWithUrlString:urlStr appendParameters:nil bodyParameters:paramters successBlock:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            [self showMessage:@"保存成功"];
            sleep(2);
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [self showMessage:responseObject[@"msg"]];
        }
    } failureBlock:^(NSError *error) {
        
    }];
}

- (void)showMessage:(NSString *)msg {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

@end
